package com.suncky.frame.base.mvp;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewbinding.ViewBinding;

import com.suncky.frame.base.BaseViewBindingFragment;

import java.lang.reflect.ParameterizedType;

public abstract class BaseMvpViewBindingFragment<B extends ViewBinding, P extends Presenter> extends BaseViewBindingFragment<B> implements IView {

    private P presenter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        presenter = createPresenter();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (presenter != null) {
            presenter.detach();
        }
    }

    public P getPresenter() {
        return presenter;
    }

    @SuppressWarnings("unchecked")
    protected P createPresenter() {
        P presenter = null;
        // 获取当前对象的父类类型
        ParameterizedType pt = (ParameterizedType) (this.getClass().getGenericSuperclass());
        if (pt != null) {
            // 获取第一个类型参数的真实类型
            Class<P> pClass = (Class<P>) pt.getActualTypeArguments()[1];
            ParameterizedType ppt = (ParameterizedType) pClass.getGenericSuperclass();
            try {
                presenter = pClass.getConstructor((Class<? extends IView>) ppt.getActualTypeArguments()[0]).newInstance(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (presenter == null) {
                try {
                    presenter = pClass.newInstance();
                    presenter.attach(this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return presenter;
    }

    @Override
    public void onPreLoading(int id) {

    }

    @Override
    public void onFinishLoading(int id) {

    }
}
